package com.liwei.vip.mall.goods.service.Impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liwei.vip.mall.goods.mapper.BrandMapper;
import com.liwei.vip.mall.goods.mapper.CategoryMapper;
import com.liwei.vip.mall.goods.mapper.SkuMapper;
import com.liwei.vip.mall.goods.mapper.SpuMapper;
import com.liwei.vip.mall.goods.model.Category;
import com.liwei.vip.mall.goods.model.Product;
import com.liwei.vip.mall.goods.model.Sku;
import com.liwei.vip.mall.goods.model.Spu;
import com.liwei.vip.mall.goods.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jackson.JsonComponentModule;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements SpuService {

    @Autowired
    private SpuMapper spuMapper;
    
    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    /**
     * 产品保存
     *
     * @param product ：组合类
     */
    @Override
    public void saveProduct(Product product) {
        //1.保存Spu
        Spu spu = product.getSpu();
        spu.setIsMarketable(1);//已上架
        spu.setIsDelete(0);//未删除
        spu.setStatus(1);//审核已通过
        spuMapper.insert(spu);
        
        //2.保存List<Sku>
        Date date = new Date();
        Category category = categoryMapper.selectById(spu.getCategoryThreeId());
        for (Sku sku : product.getSkus()) {
            //SKU名称
            //'{"适合人群":"有一定java基础的人","书籍分类":"科技"}'
            String name = spu.getName();
            Map<String,String> skuattrMap = JSON.parseObject(sku.getSkuAttribute(), Map.class);
            //循环 skuattrMap.entrySet().for
            for (Map.Entry<String, String> stringStringEntry : skuattrMap.entrySet()) {
                name+="  "+stringStringEntry.getValue();
            }
            sku.setName(name);
            //创建时间
            sku.setCreateTime(date);
            //修改时间
            sku.setUpdateTime(date);
            //分类ID
            sku.setCategoryId(spu.getCategoryThreeId());
            //分类名字
            sku.setBrandName(spu.getName());
            //品牌ID
            sku.setBrandId(spu.getBrandId());
            //品牌名字
            sku.setCategoryName(category.getName());
            //spuId
            sku.setSpuId(spu.getId());
            //状态 商品状态 1-正常，2-下架，3-删除
            sku.setStatus(1);

            //添加
            skuMapper.insert(sku);
        }
    }
}
